<?php namespace Wx\Api;

use Hdphp\Api\Api;
// use Hdphp\Wechat\Wechat;
// use Hdphp\WechatAuth\WechatAuth;
use Wx\Model\Library as LibraryModel;

class Library extends Api
{
	const API_URL_PREFIX = 'https://api.weixin.qq.com/cgi-bin';
    const MEDIA_FOREVER_UPLOAD_URL = '/material/add_material?';

	protected $db;
	// private $options;

	public function __construct()
	{
		$this->db = new LibraryModel;
		//临时改变配置项的表前缀
		Config::set('database.prefix','wx_');
		// var_dump(Config::get('database.prefix'));
		/*$this->options = array(
 			// 'token'=>'mGV77P8o2QWsTs6XBjKv6QzeetPxHkqInqN3Zf-U6sfTGRJS2lqo36IRq99eroylgd0zC8mTiCcyRR2NnVcewFbdRFjkvlM_9gGYbtgTir0', //填写你设定的key
 			// 'encodingaeskey'=>'encodingaeskey', //填写加密用的EncodingAESKey
 			'appid'=>'wxa0d181c954ae9fe1', //填写高级调用功能的app id
 			'appsecret'=>'123804fdb4de7ed9025fb80c42acf526' //填写高级调用功能的密钥
 		);*/
	}

	/**
	 * POST新增永久图片素材
	 * autor 梁子亮
	 * 2015年7月30日08:42:23
	 * @return [type] [description]
	 */
	public function addImg()
	{
		//先把上传过来的图片上传到服务器
		//获取token
		$appid=$_SESSION['appid'];
		$appsecret=$_SESSION['appsecret'];
		Weixin::appID($appid);
		Weixin::appsecret($appsecret);
		$token = Weixin::getAccessToken();
		//获得本地路径
		$files = Upload::make();
		$filename = $files[0]['dir'] . $files[0]['basename'];

		/*$data = '{
  "articles": [{
       "title": TITLE,
       "thumb_media_id": kaL5J3g2MFVoJgYW6wkyRKoTv7i1NmkxGEfcJc3RadeH9iUfMG-cZVcrE_AHHHs9,
       "author": AUTHOR,
       "digest": DIGEST,
       "show_cover_pic": SHOW_COVER_PIC(0 / 1),
       "content": CONTENT,
       "content_source_url": CONTENT_SOURCE_URL
    },
 ]
}';

		$re = self::curlPost('https://api.weixin.qq.com/cgi-bin/material/add_news?access_token=NVRhaMMu_-pNorcxTk8mFVavkRIaF5wq3VUu9T7k4dLU_ZT7jtcbpVQoRxvtKhdW8P-ngrFqsCETMJUzUMhOfRma7miw3G5YLP0dsoD7HKM',$data);
		var_dump($re);die;*/
		$type = 'image';
		$forverlibrary = Weixin::uploadForverImg($filename,$type);
		if(isset($forverlibrary['media_id']) && isset($forverlibrary['url']) )
		{
			//写到自己的数据库
			$re = Db::table('image')->insert(['name'=>'图片素材','path'=>$filename,'media_id'=>$forverlibrary['media_id'],'source'=>$forverlibrary['url'],'gid'=>0,'wxid'=>$_SESSION['wxid'],'create_at'=>time()]);
			return $re;
		}
		else
		{
			$this->error='新增失败！';
			return false;
		}
	}


	/**
	 * 新增文本素材
	 * autor 梁子亮
	 * 2015年7月28日15:27:28
	 * @return [type] [description]
	 */
	public function store()
	{
		$content = trim(Q('content'));
		if($content)
		{
			$re = Db::insert('INSERT INTO wx_text (content,create_at) VALUES(?,?)',[$content,time()]);
			return $re;
		}
		else
		{
			$this->error = '内容不能为空！';
			return false;
		}
	}

	/**
	 * ajax新增图文素材
	 * autor 梁子亮
	 * 2015年7月28日15:27:28
	 * @return [type] [description]
	 */
	public function storeWordImg()
	{
		// $content = trim(Q('content'));
		$title = Q('title','','trim');
		$author = Q('author','','trim');
		$cover = Q('cover','','trim');
		// var_dump($_FILES);die;
		$digest = Q('digest','','trim');
		$content = Q('content','','trim');
		$link = Q('link','','trim');
		
		// var_dump($title);die;

		//自动验证暂时用不了,所以先自己一个个验证
		if(!$title)
		{
			$this->error = '标题不能为空！';
			return false;
		}
		elseif (!$author) 
		{
			$this->error = '作者不能为空！';
			return false;
		}
		elseif (!$content) {
			$this->error = '内容不能为空！';
			return false;
		}
		else
		{
			$re = Db::insert('INSERT INTO wx_image_text (title,author,cover,digest,content,link,create_at) VALUES(?,?,?,?,?,?,?)',[$title,$author,$cover,$digest,$content,$link,time()]);
			var_dump($re);die;
		}

	}

	/**
	 * 获取文本列表
	 * autor 梁子亮
	 * 2015年7月28日16:33:41
	 * @return [type] [description]
	 */
	public function getWordList()
	{
		// $wxid = $_SESSION['wxid'];
		$wxid = 4;
		$data = Db::table('text')->where('wxid',$wxid)->get();
		return $data;
	}

	/**
	 * 获取图片列表
	 * autor 梁子亮
	 * 2015年7月28日16:33:41
	 * @return [type] [description]
	 */
	public function getImgList()
	{
		$wxid = $_SESSION['wxid'];
		$data = Db::table('image')->where('wxid',$wxid)->get();

		return $data;
	}

	//删除文字
	public function destroy($id)
	{
		return Db::delete('DELETE FROM wx_text WHERE id=?',[$id]);
	}

	//删除图片素材
	public function delImg()
	{
		$id = $_POST['id'];
		$media_id = Db::table('image')->where('id',$id)->pluck('media_id');
		$appid=$_SESSION['appid'];
		$appsecret=$_SESSION['appsecret'];
		Weixin::appID($appid);
		// var_dump($id);die;
		Weixin::appsecret($appsecret);
		$token = Weixin::getAccessToken();
		// var_dump($token);die;
		// $re = Weixin::delForeverMedia($media_id);
		
		//获取素材列表
		/*$data = array('type'=>'image','offset'=>0,'count'=>10);
		$re = Weixin::getForverList($data);
		var_dump($re);die;*/

		//获取素材详情
		/*$media_id = 'KOUwLURgoU4oOO5zccemwC5UM2lSiF6nBI0mwYG0YhQ';
		$re = Weixin::getForverLibraryDetails($media_id);
		var_dump($re);die;*/
		//删除微信服务器图片素材
		Weixin::delForverLibrary($media_id);
		$re =  Db::delete('DELETE FROM wx_image WHERE id=?',[$id]);
		if($re)
		{
			return true;
		}
		else
		{
			$this->error='删除失败！';
			return false;
		}
	}


	// 编辑
	public function getOldWord($id)
	{
		return Db::table('text')->where('id',$id)->first();
	}

	//更新
	public function update($id)
	{
		$content = trim($_POST['content']);
		$create_at = time();
		if(!$content)
		{
			$this->error='内容不能为空！';
			return false;
		}
		else
		{
			$a = Db::table('text')->where("id",$id)->update($_POST);
			return $a;
		}

	}

	// ajax增加封面图片
	public function uploadify()
	{
		//先把图片上传到本地服务器
		$files = Upload::make();
		$finalpath = $files[0]['dir'] . $files[0]['basename'];
		//再把图片上传到微信永久素材表中
		$appid=$_SESSION['appid'];
		$appsecret=$_SESSION['appsecret'];
		Weixin::appID($appid);
		Weixin::appsecret($appsecret);
		$token = Weixin::getAccessToken();
		$img = Weixin::uploadForverImg($finalpath,'image');
		//写到本地数据库中
		$media_id = isset($img['media_id'])?$img['media_id']:'';
		if($media_id)
		{
			$re = Db::insert('INSERT INTO wx_image (name,media_id,path,source,wxid,create_at) VALUES(?,?,?,?,?,?)',[$media_id,$media_id,$finalpath,$img['url'],$_SESSION['wxid'],time()]);
			$data = array('status'=>1,'media_id'=>$media_id,'finalpath'=>$finalpath);
			return $data;
		}
		else
		{
			$this->error='添加失败！';
			return false;
		}
	}


	/**
	 * POST新增图文素材
	 * autor 梁子亮
	 * 2015年7月30日08:42:23
	 * @return [type] [description]
	 */

	public function addWordImg()
	{
		$title = Q('title','','trim');
		$author = Q('author','','trim');
		$cover = $_FILES['cover']['name'];
		// var_dump($cover);die;
		$digest = Q('digest','','trim');
		$content = Q('editorValue','','trim');
		$link = Q('link','','trim');
		var_dump($_POST);DIE;
		//自动验证暂时用不了,所以先自己一个个验证
		if(!$title)
		{
			$this->error = '标题不能为空！';
			return false;
		}
		elseif (!$author) 
		{
			$this->error = '作者不能为空！';
			return false;
		}
		elseif (!$content) {
			$this->error = '内容不能为空！';
			return false;
		}
		elseif (!$cover) {
			$this->error = '封面图不能为空！';
			return false;
		}
		elseif (!$link) {
			$this->error = '原文链接不能为空！';
			return false;
		}
		else
		{
			/*$files = Upload::make();
			$finalpath = $files[0]['dir'] . $files[0]['basename'];
			//若果全部通过，则先把图片上传到永久素材表中
			$appid=$_SESSION['appid'];
			$appsecret=$_SESSION['appsecret'];
			Weixin::appID($appid);
			Weixin::appsecret($appsecret);
			$token = Weixin::getAccessToken();
			$img = Weixin::uploadForverImg($finalpath,'image');*/

			$media_id = isset($img['media_id'])?$img['media_id']:'';
			if($media_id)
			{
				$data = array(
					'articles'=>array(
						array(
							'title' => $title,
							'thumb_media_id' => $media_id,
							'author' => $author,
							'digest' => $digest,
							'show_cover_pic' => 1,
							'content' => $content,
							'content_source_url' => $link,
						)
					));
				$re = Weixin::addForverWordImgDetails($data);
				var_dump($re);die;
			}
			die;
			//新增永久图文素材
			$data = '{
			  "articles": [{
			       "title": "文章标题",
			       "thumb_media_id": "zVdMS2zD0bgOPGMgBEbGP7fZTjHvi-6DKsxm28QM7hU",
			       "author": "梁子亮",
			       "digest": "摘要",
			       "show_cover_pic": 1,
			       "content": "我是大帅锅，呵呵",
			       "content_source_url": "http://www.jd.com"
			    },
			 ]
			}';
			$data = '{"articles":{"title":"A","thumb_media_id":"txNzNSuy4KvSc_1cx8NV3J6kN_09Lnrkws6phZuYqrY","author":"a","digest":"A","show_cover_pic":1,"content":"A","content_source_url":"A"}}';


			$re = Db::table('image_text')->insert(['title'=>$title,'author'=>$author,'cover'=>$finalpath,'digest'=>$digest,'content'=>$content,'link'=>$link,'create_at'=>time()]);
			//如果写入到数据库成功，则生成到微信
			if($re)
			{
		        /*$Wechat = new Wechat($this->options);
		        $access_token = $Wechat->checkAuth($appid='',$appsecret='',$token='');
		        $param = '{
  "articles": [{
       "title": TITLE,
       "thumb_media_id": THUMB_MEDIA_ID,
       "author": AUTHOR,
       "digest": DIGEST,
       "show_cover_pic": SHOW_COVER_PIC(0 / 1),
       "content": CONTENT,
       "content_source_url": CONTENT_SOURCE_URL
    },
 ]
}';*/
				/*$data = array(
					'articles' =>array('title'=>'a','thumb_media_id'=>'a','author'=>'a','digest'=>'a','content'=>'a')
				);*/
				/*$url = 'https://api.weixin.qq.com/cgi-bin/material/add_news?access_token=mGV77P8o2QWsTs6XBjKv6QzeetPxHkqInqN3Zf-U6sfTGRJS2lqo36IRq99eroylgd0zC8mTiCcyRR2NnVcewFbdRFjkvlM_9gGYbtgTir0';*/

				/*$data2 = array(
						'media'=>'@\Upload/49481438235367.jpg',
					);
				$re = $Wechat->uploadMedia($data2,'image');

		        var_dump($re);die;*/

			}
		}

		
		/*$data = array(
			'articles' => array('title'=>'标题','thumb_media_id'=>'zVdMS2zD0bgOPGMgBEbGP7fZTjHvi-6DKsxm28QM7hU','author'=>'作者','digest'=>'摘要','show_cover_pic'=>1,'content'=>'内容','content_source_url'=>'http://www.jd.com')
		);*/

		/*$re = Weixin::getForverLibraryDetails('zVdMS2zD0bgOPGMgBEbGP6o35zsE92GYsw_BJYdeotA');
		var_dump($re);die;*/






		// var_dump($access_token);die;
		// var_dump($access_token);die;
		// $token = $WechatAuth->getAccessToken();
		//上传临时图片
		/*$a = $WechatAuth->mediaUpload('Upload/32351438247164.jpg','image');
		var_dump($a);die;*/
		//获取临时图片信息
		/*$mediaid = 'noCNz1G9gY0_A5jCrS9eKwcLlCkVgU3gHMNqV1AtnBwQl8EjUb4YdTzRGp6BqBUv';
		'type' => string 'image' (length=5)
		'media_id' => string 'mM5LDK7R5KHui5E2YV5WFLXfI7919Z-gkWNkYVhbgAJQ-UVdn8L0vamVfbUXMQ99' (length=64)
		'created_at' => int 1438276756
		$b = $WechatAuth->mediaGet($mediaid);
		var_dump($b);die;*/
		//string '@S:\wamp2\www\weixin\cms\Upload\32351438247164.jpg' (length=50)


		//上传永久图片
		/*$b = $WechatAuth->mediaUploadlzl('Upload/32351438247164.jpg','image');
		var_dump($b);die;
		'media_id' => string 'KOUwLURgoU4oOO5zccemwC5UM2lSiF6nBI0mwYG0YhQ' (length=43)
  'url' => string 'https://mmbiz.qlogo.cn/mmbiz/KHFYqNl5aG9E3dDxffqAAdtAGYIZYqjQjq3WcD71MNPfZtzcKOLT9Kfd2e96nsOVQwKBoPpDsAcTvOwnMQic28Q/0?wx_fmt=jpeg' (length=130)*/

		/*$data2 = '{
  "articles": [{
       "title": TITLE,
       "thumb_media_aid": "KOUwLURgoU4oOO5zccemwC5UM2lSiF6nBI0mwYG0YhQ",
       "author": AUTHOR,
       "digest": DIGEST,
       "show_cover_pic": SHOW_COVER_PIC(0 / 1),
       "content": CONTENT,
       "content_source_url": CONTENT_SOURCE_URL
    },
 ]
}';*/
		/*$data3 = array(
			'articles'=>array(
				"title" =>'a',
				"thumb_media_id" =>'noCNz1G9gY0_A5jCrS9eKwcLlCkVgU3gHMNqV1AtnBwQl8EjUb4YdTzRGp6BqBUv',
				"author" =>'a',
				"digest" =>'a',
				"show_cover_pic" =>1,
				"content" =>'a',
				"content_source_url" =>'www.baidu.com'
			)

		);*/
		// var_dump(json_encode($data));die;
		/*//用hdweixin自带的curlPost方法尝试增加永久素材失败
		$url = 'https://api.weixin.qq.com/cgi-bin/material/add_news?access_token=aa2xxHIZ37HmSN2ngAD2IQ-DsXiOF3aCMfJPry3I1PVpQAl7AafFVdKvIY_qszKzoHpAunHTMRy1lUc1raktn_pzNyytzXUKXR7AWqr_P_I';
		$c = $this->curlPost($url,$data2);
		var_dump($c);die;*/

		/*//用WeChat的上传永久素材方法尝试
		$url = 'https://api.weixin.qq.com/cgi-bin/material/add_news?access_token=aa2xxHIZ37HmSN2ngAD2IQ-DsXiOF3aCMfJPry3I1PVpQAl7AafFVdKvIY_qszKzoHpAunHTMRy1lUc1raktn_pzNyytzXUKXR7AWqr_P_I';
		$WeChat = new WeChat();
		$c = $WeChat->uploadForeverMedia(array('media' => '@S:\wamp2\www\weixin\cms\Upload\32351438247164.jpg'),'image');
		var_dump($c);die;*/

		
	}


	//上传永久素材
	public function uploadForeverMedia($data, $type,$is_video=false,$video_info=array(),$access_token){
        // if (!$this->access_token && !$this->checkAuth()) return false;
        //#TODO 暂不确定此接口是否需要让视频文件走http协议
        //如果要获取的素材是视频文件时，不能使用https协议，必须更换成http协议
        //$url_prefix = $is_video?str_replace('https','http',self::API_URL_PREFIX):self::API_URL_PREFIX;
        //当上传视频文件时，附加视频文件信息
        if ($is_video) $data['description'] = self::json_encode($video_info);
        $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_FOREVER_UPLOAD_URL.'access_token='.$access_token.'&type='.$type,$data,true);
        var_dump($result);die;
        if ($result)
        {
            $json = json_decode($result,true);
            if (!$json || !empty($json['errcode'])) {
                $this->errCode = $json['errcode'];
                $this->errMsg = $json['errmsg'];
                return false;
            }
            return $json;
        }
        return false;
    }


    /**
	 * 微信api不支持中文转义的json结构
	 * @param array $arr
	 */
	static function json_encode($arr) {
        $parts = array ();
        $is_list = false;
        //Find out if the given array is a numerical array
        $keys = array_keys ( $arr );
        $max_length = count ( $arr ) - 1;
        if (($keys [0] === 0) && ($keys [$max_length] === $max_length )) { //See if the first key is 0 and last key is length - 1
            $is_list = true;
            for($i = 0; $i < count ( $keys ); $i ++) { //See if each key correspondes to its position
                if ($i != $keys [$i]) { //A key fails at position check.
                    $is_list = false; //It is an associative array.
                    break;
                }
            }
        }
        foreach ( $arr as $key => $value ) {
            if (is_array ( $value )) { //Custom handling for arrays
                if ($is_list)
                    $parts [] = self::json_encode ( $value ); /* :RECURSION: */
                else
                    $parts [] = '"' . $key . '":' . self::json_encode ( $value ); /* :RECURSION: */
            } else {
                $str = '';
                if (! $is_list)
                    $str = '"' . $key . '":';
                //Custom handling for multiple data types
                if (!is_string ( $value ) && is_numeric ( $value ) && $value<2000000000)
                    $str .= $value; //Numbers
                elseif ($value === false)
                $str .= 'false'; //The booleans
                elseif ($value === true)
                $str .= 'true';
                else
                    $str .= '"' . addslashes ( $value ) . '"'; //All other things
                // :TODO: Is there any more datatype we should be in the lookout for? (Object?)
                $parts [] = $str;
            }
        }
        $json = implode ( ',', $parts );
        if ($is_list)
            return '[' . $json . ']'; //Return numerical JSON
        return '{' . $json . '}'; //Return associative JSON
    }


    /**
	 * POST 请求
	 * @param string $url
	 * @param array $param
	 * @param boolean $post_file 是否文件上传
	 * @return string content
	 */
	private function http_post($url,$param,$post_file=false){
		$oCurl = curl_init();
		if(stripos($url,"https://")!==FALSE){
			curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
			curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
			curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
		}
		if (is_string($param) || $post_file) {
			$strPOST = $param;
		} else {
			$aPOST = array();
			foreach($param as $key=>$val){
				$aPOST[] = $key."=".urlencode($val);
			}
			$strPOST =  join("&", $aPOST);
		}
		curl_setopt($oCurl, CURLOPT_URL, $url);
		curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt($oCurl, CURLOPT_POST,true);
		curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
		$sContent = curl_exec($oCurl);
		$aStatus = curl_getinfo($oCurl);
		curl_close($oCurl);
		if(intval($aStatus["http_code"])==200){
			return $sContent;
		}else{
			return false;
		}
	}

	//curl 提交数据
    private function curlPost($url,$jsonData)
    {
        $ch = curl_init();  
        curl_setopt($ch, CURLOPT_URL, $url);  
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);  
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);  
        curl_setopt($ch, CURLOPT_POST, 1);  
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);  
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);  
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
        $data = curl_exec($ch);
        curl_close($ch);  
        return $data;
    }

    /**
     * GET 请求
     * @param string $url
     */
    private function http_get($url){
        $oCurl = curl_init();
        if(stripos($url,"https://")!==FALSE){
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if(intval($aStatus["http_code"])==200){
            return $sContent;
        }else{
            return false;
        }
    }

    //CURL请求
    private function curl($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        if(!curl_exec($ch))
        {
            $data='';
        }
        else
        {
            $data = curl_multi_getcontent($ch);
        }
        curl_close($ch);
        return $data;
    }
}